//
//  VideoChatViewController.m
//  VideoChat
//
//  Created by user on 2019/3/22.
//  Copyright © 2019 烧烤有点辣. All rights reserved.
//

#import "VideoChatViewController.h"

#import "CaptureView.h"
#import "ShowOpenGLView.h"
#import "DecodeH264Manner.h"
#import "EncodeH264Manner.h"

#import "TMAudioDecoder.h"
#import "TMAudioPCMPlayer.h"
#import "TMAVConfig.h"
#import "TMAudioEncoder.h"

#import "DNKUdpRequestManager.h"

#define KPort 38889

@interface VideoChatViewController ()<H264EncoderDelegate, DecodeH264Delegate, TMAudioDecoderDelegate, TMAudioEncoderDelegate>

@property (nonatomic, strong) CaptureView *videView;

@property (nonatomic, strong) ShowOpenGLView *openglView;
@property (nonatomic, strong) EncodeH264Manner *encodeH264;
@property (nonatomic, strong) DecodeH264Manner *decodeH264;

@property (nonatomic, strong) TMAudioEncoder *audioEncoder;
@property (nonatomic, strong) TMAudioDecoder *audioDecoder;
@property (nonatomic, strong) TMAudioPCMPlayer *pcmPalyer;

@end

@implementation VideoChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.encodeH264 = [[EncodeH264Manner alloc] init];
    self.encodeH264.delegate = self;
    [self.encodeH264 initVideoToolBoxWithWidth:800 height:600];
    
    self.decodeH264 = [[DecodeH264Manner alloc] init];
    self.decodeH264.delegate = self;
    [self.decodeH264 initH264DecoderWithWidth:800 height:600];
    
    __weak typeof(self) weakSelf = self;
    self.videView = [[CaptureView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height/2-20) DidOutputSampleBufferBlock:^(CMSampleBufferRef sampleBuffer, AVMediaType mediaType) {
        if (mediaType == AVMediaTypeVideo) {
            [weakSelf.encodeH264 encode:sampleBuffer];
        } else if (mediaType == AVMediaTypeAudio) {
            [_audioEncoder encodeAudioSamepleBuffer:sampleBuffer];
        }
        
    }];
    [self.videView setBackgroundColor:[UIColor grayColor]];
    [self.view addSubview:self.videView];
    
    self.openglView = [[ShowOpenGLView alloc] init];
    self.openglView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height/2-20, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height/2);
    [self.view addSubview:self.openglView];
    [self.openglView setupGL];
    
    
    //aac编码器
    _audioEncoder = [[TMAudioEncoder alloc] initWithConfig:[TMAudioConfig defaultConifg]];
    _audioEncoder.delegate = self;
    
    //aac解码器
    _audioDecoder = [[TMAudioDecoder alloc] initWithConfig:[TMAudioConfig defaultConifg]];
    _audioDecoder.delegate = self;
    
    //pcm播放器
    _pcmPalyer = [[TMAudioPCMPlayer alloc] initWithConfig:[TMAudioConfig defaultConifg]];
    
    
    [[DNKUdpRequestManager shareUdpManager] CallMessageSuccessBlock:^(NSData *data, NSData *address, NSInteger tag) {
        if ([[[DNKUdpRequestManager shareUdpManager] hostFromAddress:address] isEqualToString:self.addressIP]) {
            NSMutableData *getData = [[NSMutableData alloc] initWithData:data];
            const char bytes[] = "\x00\x00\x00\x01";
            size_t length = (sizeof bytes) - 1;
            NSData *byteHeader = [NSData dataWithBytes:bytes length:length];
            NSData *subData =[getData subdataWithRange:NSMakeRange(0, 4)];
            if ([subData isEqualToData:byteHeader]) {
                [self.decodeH264 decodeNalu:(uint8_t *)[data bytes] withSize:(uint32_t)data.length];
            } else {
                 [_audioDecoder decodeAudioAACData:data];
            }
        }
        
    } failureBlock:nil];
    
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.videView starVideo];
}

- (void)gotSpsPps:(NSData*)sps pps:(NSData*)pps ByteHeader:(NSData *)byteHeader {
    NSMutableData *h264Data = [[NSMutableData alloc] init];
    [h264Data appendData:byteHeader];
    [h264Data appendData:sps];
//    [self.decodeH264 decodeNalu:(uint8_t *)[h264Data bytes] withSize:(uint32_t)h264Data.length];
    [[DNKUdpRequestManager shareUdpManager] sendUdpWithData:h264Data toIp:self.addressIP port:KPort Timeout:-1 tag:100];
    
    //pps
    [h264Data resetBytesInRange:NSMakeRange(0, [h264Data length])];
    [h264Data setLength:0];
    [h264Data appendData:byteHeader];
    [h264Data appendData:pps];
    [[DNKUdpRequestManager shareUdpManager] sendUdpWithData:h264Data toIp:self.addressIP port:KPort Timeout:-1 tag:100];
//    [self.decodeH264 decodeNalu:(uint8_t *)[h264Data bytes] withSize:(uint32_t)h264Data.length];
}

- (void)gotEncodedData:(NSData *)data ByteHeader:(NSData *)byteHeader isKeyFrame:(BOOL)isKeyFrame {
    
    NSMutableData *h264Data = [[NSMutableData alloc] init];
    [h264Data appendData:byteHeader];
    [h264Data appendData:data];
    
    [[DNKUdpRequestManager shareUdpManager] sendUdpWithData:h264Data toIp:self.addressIP port:KPort Timeout:-1 tag:100];
//    [self.decodeH264 decodeNalu:(uint8_t *)[h264Data bytes] withSize:(uint32_t)h264Data.length];
}

- (void)displayDecodedFrame:(CVImageBufferRef)imageBuffer {
    [self.openglView displayPixelBuffer:imageBuffer];
}

//aac编码回调
- (void)audioEncodeCallback:(NSData *)aacData {
    
    [[DNKUdpRequestManager shareUdpManager] sendUdpWithData:aacData toIp:self.addressIP port:KPort Timeout:-1 tag:100];
    
//    [_audioDecoder decodeAudioAACData:aacData];
}

- (void)audioDecodeCallback:(NSData *)pcmData {
    //解码后播放
    [_pcmPalyer playPCMData:pcmData];
}

@end
